<template>
    <f7-page class="no-toolbar no-navbar no-swipeback">
        <f7-block class="center login-logo text-align-center"
                  style="margin: 64px auto;">
            <img src="../../assets/img/logo-qm.png"
                 height="80"
                 style="border-radius:21%" />
            <h2 class="title"
                style="font-size: 20px;margin-top: 10px;">齐明软件-APP框架 5.0.0</h2>
        </f7-block>

        <!-- <div class="window-tools"
             v-if="packageType != 'app'">
            <f7-button @click="resize('window-min')"
                       class="oper_btn">
                <f7-icon f7="minus"></f7-icon>
            </f7-button>
            <f7-button @click="resize('window-max')"
                       class="oper_btn">
                <f7-icon f7="app"></f7-icon>
            </f7-button>
            <f7-button class="oper_btn"
                       @click="resize('window-close')"
                       style="font-size: 30px;line-height: 30px;">
                <f7-icon f7="xmark"></f7-icon>
            </f7-button>
        </div> -->

        <f7-block strong
                  inset>
            <f7-list no-hairlines-md
                     style="margin-bottom: 8px;">
                <f7-list-input type="text"
                               placeholder="请输入账号"
                               name="loginId"
                               :value="loginId"
                               @change="loginId = $event.target.value"
                               clear-button
                               autofocus></f7-list-input>
                <f7-list-input type="password"
                               placeholder="请输入密码"
                               :value="password"
                               @change="password = $event.target.value"
                               clear-button></f7-list-input>
            </f7-list>
            <f7-button large
                       @click="login">登&nbsp;&nbsp;录</f7-button>
            <!-- <f7-button large @click="wechatLogin(true)">测试微信登录(自动注册新账号)</f7-button>
      <f7-button large @click="wechatLogin(false)">测试微信登录(需已绑定现有账号)</f7-button> -->
        </f7-block>

        <!-- <f7-fab position="right-bottom" slot="fixed" text="指纹登录" @click="finderLogin">
      <f7-icon f7="viewfinder"></f7-icon>
    </f7-fab>-->
    </f7-page>
</template>
<script>
import Config from "@/libs/config";
export default {
    data () {
        return {
            loginId: "",
            password: "",
            oauthType: "LOCAL",
            appCode: this.$f7.id || window.plus.runtime.appid,
            packageType: Config.setting.packageType,
            rsaPublic: ""
        };
    },
    created () {
        this.loadRsaPublic();
        this.getCode();
    },
    computed: {
        company: function () {
            return "2020 ©" + this.$framework.config.info.company;
        }
    },
    methods: {
        loadRsaPublic () {
            this.$framework.account.getRsaPublic().then(rsaPublic => {
                this.rsaPublic = rsaPublic;
            });
        },
        login () {
            if (!this.loginId) {
                this.$f7.dialog.toast("请输入用户名");
            } else if (!this.password) {
                this.$f7.dialog.toast("请输入密码");
            } else {
                const principal = this.$framework.account.getLoginEncryptorParam(this.loginId, this.password, this.rsaPublic);
                if (!principal) {
                    this.$f7.dialog.toast("用户名或密码错误！");
                } else {
                    this.$f7.preloader.show();
                    this.$framework.account.login({
                        principal: principal,
                        oauthType: "LOCAL",
                        appCode: this.$f7.id || window.plus.runtime.appid,
                        packageType: Config.setting.packageType,
                    }, r => {
                        this.$f7.preloader.hide();

                        if (r.success) {
                            this.goToHomePage();
                            //this.$framework.redirect.home();
                            // this.$f7.dialog.toast("登录成功");
                        } else {
                            this.$f7.dialog.alert(r.message);
                            this.getCode();
                        }
                    });
                }
            }
        },
        goToHomePage () {
            this.$util
                .request(
                    "/app/ent/entPersonBase/getPersonBaseByCurrentUser",
                    {},
                    "post"
                )
                .then((res) => {
                    if (res.data.parameters) {
                        let status = res.data.parameters.status;
                        if (status == 1) {
                            this.$framework.redirect.home();
                        } else if (status == 2) {
                            this.getWorkflowArgs({ formId: res.data.parameters.entPerson.caseId }).then(rlt => {
                                let url = "";
                                rlt.appUrl = '/business/qzjx/bindUnit/create'
                                if (rlt.taskId) {
                                    url = `${rlt.appUrl}?action=processEdit&taskId=${rlt.taskId}&assigneeId=${rlt.assigneeId}&appCode=${rlt.appCode}&version=${rlt.version}&_r=${new Date().getTime()}`;
                                } else if (rlt.historyTaskId) {
                                    url = `${rlt.appUrl}?action=processView&historyTaskId=${rlt.historyTaskId}&appCode=${rlt.appCode}&version=${rlt.version}&_r=${new Date().getTime()}&assigneeId=${rlt.assigneeId}`;
                                } else {
                                    this.$toast("无法获取应用的处理地址");
                                }
                                if (url) {
                                    this.$f7router.navigate(url);
                                }
                            })
                        } else {
                            this.$f7router.navigate('/business/qzjx/bindUnit/index');
                        }
                    }
                });
        },
        finderLogin () {
            if (!window.plus) {
                this.$f7.dialog.alert("不是手机端，无法使用指纹登录");
                return;
            }
            if (!window.plus.fingerprint) {
                this.$f7.dialog.alert(
                    "当前环境不支持指纹识别API，请联系管理员更新到最新版本"
                );
                return;
            }
            let isSupport = window.plus.fingerprint.isSupport();
            if (!isSupport) {
                this.$f7.dialog.alert("您的手机不支持指纹登录，请输入账号密码登录");
                return;
            }
            let isKeygardSecure = window.plus.fingerprint.isKeyguardSecure();
            if (!isKeygardSecure) {
                this.$f7.dialog.alert("您没有设置密码锁屏，无法使用指纹登录");
                return;
            }
            let isEnrolledFingerprints = window.plus.fingerprint.isEnrolledFingerprints();
            if (!isEnrolledFingerprints) {
                this.$f7.dialog.alert("您的设备还没有录入指纹，无法使用指纹登录");
                return;
            }
            var waiting = null;
            window.plus.fingerprint.authenticate(
                function () {
                    window.plus.nativeUI.closeWaiting(); //兼容Android平台关闭等待框
                    console.log("指纹识别成功");
                },
                function (e) {
                    switch (e.code) {
                        case e.AUTHENTICATE_MISMATCH:
                            window.plus.nativeUI.toast("指纹匹配失败，请重新输入");
                            break;
                        case e.AUTHENTICATE_OVERLIMIT:
                            window.plus.nativeUI.closeWaiting(); //兼容Android平台关闭等待框
                            window.plus.nativeUI.alert(
                                "指纹识别失败次数超出限制，请使用其它方式进行登录"
                            );
                            break;
                        default:
                            window.plus.nativeUI.closeWaiting(); //兼容Android平台关闭等待框
                            window.plus.nativeUI.alert(
                                "指纹识别失败(" + e.code + ")，请重试"
                            );
                            break;
                    }
                }
            );
            // Android平台弹出等待提示框
            if ("Android" == plus.os.name) {
                window.plus.nativeUI.showWaiting("指纹识别中...");
            }
        },
        wechatLogin (type) {
            let self = this;
            if (!window.plus) {
                this.$f7.dialog.alert("不是手机端无法使用微信登录!");
                return;
            }
            plus.oauth.getServices(
                function (services) {
                    let auths = services;
                    for (var i in services) {
                        let service = services[i];
                        auths[service.id] = service;
                    }
                    let aweixin = auths["weixin"];
                    if (!aweixin) {
                        plus.nativeUI.alert("当前环境不支持微信登录");
                        return;
                    }

                    new Promise((rs, rj) => {
                        if (!aweixin.authResult) {
                            // aweixin.authorize(
                            //   function(e) {
                            //     console.log("授权码：", e.code); //app端获取到的code

                            //     aweixin.login(
                            //       function(e) {
                            //         rs(e.target);
                            //       },
                            //       function(e) {
                            //         rj(new Error("登录认证失败: " + JSON.stringify(e)));
                            //       }
                            //     );
                            //   },
                            //   function(e) {
                            //     plus.nativeUI.alert("授权失败："+JSON.stringify(e));
                            //     rj(new Error("微信授权失败"));
                            //   },
                            //   {
                            //     scope: "snsapi_userinfo",
                            //     state: "authorize test",
                            //   }
                            // );
                            aweixin.login(
                                function (e) {
                                    rs(e.target);
                                },
                                function (e) {
                                    rj(new Error("登录认证失败: " + JSON.stringify(e)));
                                },
                                {
                                    scope: "snsapi_userinfo",
                                    state: "authorize test"
                                }
                            );
                        } else {
                            rs(aweixin);
                        }
                    })
                        .then(rlt => {
                            let accessToken = rlt.authResult.access_token;
                            let openid = rlt.authResult.openid;
                            let nickname = rlt.userInfo.nickname;
                            let params = {
                                openid: openid,
                                accessToken: accessToken,
                                nickname: nickname,
                                oauthType: "WEIXIN",
                                auto_register: type
                            };

                            self.$framework.account.wechatLogin(params);
                        })
                        .catch(err => {
                            plus.nativeUI.alert(err);
                        });
                },
                function (e) {
                    plus.nativeUI.alert("获取登录授权服务列表失败：" + JSON.stringify(e));
                }
            );
        },
        getCode () {
            // this.$('img.vcode').attr('src', this.$framework.util.mapApi(framework.api.vcode) + "?_r=" + Math.random());
        },
        register () {
            this.$framework.redirect.register();
        },
        resize (type) {
            if (type == "window-close") {
                this.$f7.dialog.confirm("确定退出应用吗？", r => {
                    if (r) {
                        window.ipcRenderer.send(type);
                    }
                });
            } else {
                window.ipcRenderer.send(type);
            }
        }
    }
};
</script>

<style scoped>
.oper_btn {
    color: var(--f7-navbar-text-color, var(--f7-bars-text-color)) !important;
    display: inline-block !important;
}
.window-tools {
    right: 10px;
    top: 10px;
    position: absolute !important;
}
.window-tools .button i.narrow {
    display: inline-block;
    width: 18px;
    height: 2px;
    background: #aaa;
    margin-bottom: 7px;
}
.window-tools .button i.enlarge {
    display: inline-block;
    width: 15px;
    height: 13px;
    border: 2px solid #aaa;
}
.window-tools .button {
    color: #aaa;
    border: 0px none;
    line-height: 37px;
}
.window-tools a + a {
    margin-left: 3px;
}
</style>
